import Vue from 'vue'
import Router from 'vue-router'
import User from './user/user'
import Admin from './admin/admin'
import store from '../store'
import Error from './error/error'
// import { Alert } from '../base/index'
Vue.use(Router)

const redirectRouter = [{
  path: '/',
  redirect: {
    name: 'user'
  }
}]
let router = new Router({
  routes: [
    ...redirectRouter,
    ...User,
    ...Error,
    ...Admin
  ],
  mode: 'history',
  base: '/'
})
// router.beforeEach((to, from, next) => {
//   console.log(this.$router, to.path)
//   if (to.matched.length === 0) {
//     from.name ? next({ name: from.name }) : next('/error')
//   } else {
//     if (to.meta.isNoCheck) {
//       next()
//     } else {
//       next()
//       if (store.state.userInfo.length > 0) {
//         next()
//       } else {
//         // if (to.name !== 'login') {
//         //   next({ name: 'user' })
//         //   this.$message.error('你还未登陆')
//         // }
//       }
//     }
//   }
// })
router.beforeEach((to, from, next) => {
  console.log(this.$router, to.path)
  // console.log(gloablData)
  if (to.path !== '/user/login') {
    // var _token = to.query.token
    // // let _navList = gloablData.navList
    // let _last = to.path.split('/')
    // let _qx = store.state.navListCan
    // if (_navList[_last[1]]) {
    //   if (_qx.includes(_navList[_last[1]][_last[2]])) {
    //     next()
    //   } else {
    //     for (let item in _navList[_last[1]]) {
    //       if (_qx.includes(_navList[_last[1]][item])) {
    //         // next({ path: '/' + _last[1] + '/' + item })
    //         // return
    //         next({ path: '/' + _last[1] + '/' + item })
    //         break
    //       }
    //     }
    //   }
    // }
    let _token = store.state.userInfo.token
    console.log(store, _token, 'store')
    if (_token && _token.length > 0) {
      if (to.matched.length === 0) {
        from.name ? next({ name: from.name }) : next('/error')
      } else {
        if (to.meta.isNoCheck) {
          next()
        } else {
          next()
          if (store.state.userInfo.length > 0) {
            next()
          } else {
            // if (to.name !== 'login') {
            //   next({ name: 'user' })
            //   this.$message.error('你还未登陆')
            // }
          }
        }
      }
      // next()
    } else {
      let _loToken = window.localStorage.getItem('__userInfo__')
      console.log(_loToken)
      if (_loToken) {
        next()
      } else {
        next({ path: '/user/login' })
      }
      // next({ path: '/user/login' })
    }
  } else {
    next()
  }
})
router.afterEach((to, from, next) => {
  let routerTitle = ''
  if (to.meta.title) {
    routerTitle = `${to.meta.title}`
  } else {
    routerTitle = 'fangcun'
  }
  document.title = routerTitle
})
export default router
